package com.barneyx.mshinfoplatform.web.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.barneyx.mshinfoplatform.common.ExResult;
import com.barneyx.mshinfoplatform.entity.info.InfoSettingEntity;
import com.barneyx.mshinfoplatform.service.info.IInfoSettingEntityService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/admin/info/settings/")
public class AdminInfoSettingController {

    @Resource
    private IInfoSettingEntityService infoSettingEntityService;


    @GetMapping("settings-by-id")
    public ExResult<?> getSettingsById(@RequestParam("id") String settingId) {
        InfoSettingEntity setting = infoSettingEntityService.getById(settingId);
        return ExResult.ofAuto(setting);
    }

    @GetMapping("settings-by-code")
    @CachePut(value = "INFO_SETTING", key = "#settingCode")
    public ExResult<?> getSettingsByCode(@RequestParam("code") String settingCode) {
        InfoSettingEntity setting = infoSettingEntityService.getOne(new LambdaQueryWrapper<InfoSettingEntity>()
                .eq(InfoSettingEntity::getInfoSettingCode, settingCode));
        return ExResult.ofAuto(setting);
    }

    @GetMapping("/settings-by-areaid")
    public ExResult<?> getAreasById(@RequestParam("areaid") String areaId) {
        List<InfoSettingEntity> list = infoSettingEntityService.list(new LambdaQueryWrapper<InfoSettingEntity>()
                .eq(InfoSettingEntity::getAreaId, areaId));
        return ExResult.ofAuto(list);
    }


    @PutMapping("save-setting")
    @CacheEvict(value = "INFO_SETTING", key = "#infoSetting.getInfoSettingCode()")
    public ExResult<?> saveSetting(@RequestBody InfoSettingEntity infoSetting) {
        boolean update = infoSettingEntityService.update(new LambdaUpdateWrapper<InfoSettingEntity>()
                .eq(InfoSettingEntity::getInfoSettingId, infoSetting.getInfoSettingId())
                .set(InfoSettingEntity::getInfoSettingContent, JSONObject.toJSONString(infoSetting.getInfoSettingContent()))
                .set(InfoSettingEntity::getInfoSettingValue, infoSetting.getInfoSettingValue()));
        return ExResult.ofAuto(update);
    }
}
